package com.goldsprite.gsgecs.systems;

import com.goldsprite.gsgecs.entities.GameObject;
import com.goldsprite.gsgecs.entities.IGameObject;

import java.util.HashMap;
import java.util.Map;
import com.goldsprite.gsgecs.GameLoop;

public class GameObjectManager extends GameLoop implements IGameObjectManager {
	private static int uuidSeed = 0; // 静态计数器用于生成唯一 ID
	private final static Map<String, IGameObject> entities = new HashMap<>(); // ID 和 GameObject 的映射
	private static GameObjectManager instance;

	public GameObjectManager(){
		synchronized(GameObjectManager.class){
			if(instance != null) throw new RuntimeException("非法创建实例，仅允许1个EntitySystem实例存在");
			instance = this;
		}
	}

	public String getUuidSeed() {
		return String.valueOf(uuidSeed);
	}

	public static GameObjectManager getInstance(){
		return instance;
	}

	public GameObject instantiateEntity(GameObject entity){
		uuidSeed++;
		entities.put(entity.getUuid(), entity);
		return entity;
	}

	@Override
	public void addEntity(IGameObject gameObject) {
		if (entities.containsKey(gameObject.getUuid())) {
			throw new IllegalArgumentException(
				"GameObject with id already exists: " + gameObject.getUuid());
		}
		entities.put(gameObject.getUuid(), gameObject);
	}

	@Override
	public void destroyEntity(IGameObject entity) {
		if (!entities.containsValue(entity)) {
			throw new IllegalArgumentException("未找到目标实体: " + entity);
		}
		destroyEntity(entity.getUuid());
	}

	@Override
	public void destroyEntity(String id) {
		if (!entities.containsKey(id)) {
			throw new IllegalArgumentException(": " + id);
		}
		entities.remove(id);
	}

	@Override
	public IGameObject getEntity(String id) {
		return entities.get(id); // 查找方法
	}

	@Override
	public void start(){
		entities.forEach((id, ent)->{
			if(ent.isEnable()) ent.start();
		});
	}

	@Override
	public void fixedUpdate(float fixedDelta) {
		entities.forEach((id, ent)->{
			ent.fixedUpdate(fixedDelta);
		});
	}

	@Override
	public void update(float delta) {
		entities.forEach((id, ent)->{
			ent.update(delta);
		});
	}

	@Override
	public void destroy() {
		entities.forEach((id, ent)->{
			destroyEntity(id);
		});
	}

}
